/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.payment.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.ConvertUpMoneyUtil;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.common.utils.PdfUtil;
import com.icinfo.cloud.provider.common.zzd.DingDingUtil;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.service.IElectricInvoiceInterface;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.systemmessage.dto.SystemMessageInsertDto;
import com.icinfo.cloud.provider.punish.common.systemmessage.service.ICaseSystemMessageService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseMainDetailAuxiliaryInfoRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseHandlePersonRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.*;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentResultRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.model.PaymentResultInfo;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentItemDetailService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentResultRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentItemDetailVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentResultRecordVo;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.dto.ExecuteFinishAutomaticInfoDto;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.service.ICaseExecuteService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 描述: 案件缴款结果记录表 case_payment_result_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月02日
 */
@Service
@Slf4j
public class CasePaymentResultRecordServiceImpl extends MyBatisServiceSupport implements ICasePaymentResultRecordService {
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;
    @Resource
    private ICasePaymentMainRecordService casePaymentMainRecordService;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICasePaymentItemDetailService casePaymentItemDetailService;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private ICaseExecuteService caseExecuteService;
    @Resource
    private IElectricInvoiceInterface electricInvoiceInterface;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    @Resource
    private ICaseSystemMessageService caseSystemMessageService;

    @Value("${paymentUnified.url}")
    private String paymentUnifiedUrl;
    @Value("${paymentUnified.uri.getPaymentResultInfo}")
    private String getPaymentResultInfoUri;
    @Value("${paymentCq.busQueryPayStatusUrl}")
    private String busQueryPayStatusUrl;

    /**
     * 【V1.0.0】描述：保存案件缴款结果记录信息
     *
     * @param saveDto {@link CasePaymentResultRecordSaveDto}
     * @return {@link Result <String>} 保存结果
     * @author xiangyuyu
     * @date 2022-03-02 15:23
     */
    @Override
    public Result<String> saveCasePaymentResultRecordInfo(CasePaymentResultRecordSaveDto saveDto) {
        log.info("saveCasePaymentResultRecordInfo start...saveDto:{}", saveDto);
        if(!ObjectUtils.isEmpty(saveDto.getElectricInvoiceInfo())){
            System.out.println("ElectricInvoiceInfo+++:"+saveDto.getElectricInvoiceInfo().get(0));
        }
        String noticeNo = saveDto.getNoticeNo();
        if (ObjectUtils.isEmpty(noticeNo)) {
            return Result.error("未指定缴款单号");
        }
        //根据缴款单号查询案件id
        CasePaymentMainRecordQueryDto queryDto = new CasePaymentMainRecordQueryDto();
        queryDto.setNoticeNo(noticeNo);
        List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryDto);
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            return Result.error("未匹配到缴款信息");
        }
        CasePaymentMainRecordVo vo = list.get(Constant.INTEGER_0);
        String uid = BaseUtil.createUid();
        CasePaymentResultRecord casePaymentResultRecord = new CasePaymentResultRecord();

        BeanUtils.copyProperties(saveDto, casePaymentResultRecord);
        String caseId = vo.getCaseId();
        casePaymentResultRecord.setCaseId(caseId);
        casePaymentResultRecord.setId(uid);
        casePaymentResultRecord.setDealStatus(YesOrNoEnum.NO.getCode());

        Example update = new Example(CasePaymentResultRecord.class);
        update.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("noticeNo", noticeNo)
                .andNotEqualTo("id", uid);
        CasePaymentResultRecord record = new CasePaymentResultRecord();
        record.setIsDelete(YesOrNoEnum.YES.getCode());
        int deleteCount = casePaymentResultRecordMapper.updateByExampleSelective(record, update);
        log.info("deleteCount:{}", deleteCount);
        int insertCount = casePaymentResultRecordMapper.insertSelective(casePaymentResultRecord);
        log.info("insertCount:{}", insertCount);
        saveDto.setCaseId(caseId);
        log.info("saveCasePaymentResultRecordInfo end!");
        saveDto.setEnterCode(vo.getEnterCode());
        String afterDealMsg = serviceDealAfterSaveCasePaymentResult(saveDto);
        return Result.success("saveCasePaymentResultRecordInfo:" + Constant.STRING_SAVE_SUCCESS + ",serviceDealAfterSaveCasePaymentResult:" + (ObjectUtils.isEmpty(afterDealMsg) ? Constant.STRING_OPERATE_SUCCESS : afterDealMsg));
    }


    /**
     * 【V1.0.0】描述：保存案件缴款结果后续业务处理
     *
     * @param dto {@link CasePaymentResultRecordSaveDto}
     * @return String 处理结果错误信息
     * @author xiangyuyu
     * @date 2022-07-06 19:22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String serviceDealAfterSaveCasePaymentResult(CasePaymentResultRecordSaveDto dto) {
        log.info("serviceDealAfterSaveCasePaymentResult start...dto:{}", dto);
        String returnMsg = "";
        CasePaymentResultRecord casePaymentResultRecord = new CasePaymentResultRecord();
        String caseId = null;
        try {
            String noticeNo = dto.getNoticeNo();
            if (ObjectUtils.isEmpty(noticeNo)) {
                throw new BusinessException("未指定缴款单号");
            }
            //根据缴款单号查询案件id
            CasePaymentMainRecordQueryDto queryDto = new CasePaymentMainRecordQueryDto();
            queryDto.setNoticeNo(noticeNo);
            List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryDto);
            if (ObjectUtils.isEmpty(list) || list.size() == 0) {
                throw new BusinessException("未匹配到缴款信息");
            }
            CasePaymentMainRecordVo vo = list.get(Constant.INTEGER_0);
            dto.setEnterCode(vo.getEnterCode());
            caseId = vo.getCaseId();
            BeanUtils.copyProperties(dto, casePaymentResultRecord);
            String uid = BaseUtil.createUid();
            casePaymentResultRecord.setId(uid);
            casePaymentResultRecord.setCaseId(caseId);
            dto.setCaseId(caseId);
            String payDate = dto.getPayDate();
            casePaymentResultRecord.setDealStatus(YesOrNoEnum.YES.getCode());
            int updateCount = updatePaymentResultInfoAfterDeal(casePaymentResultRecord);
            log.info("updateCount:{}", updateCount);
            //更新缴款单为已缴款
            int successCount = casePaymentMainRecordService.updateCasePaymentMainRecordStatusByNoticeNo(noticeNo, PayStatusEnum.PAID.getCode());
            log.info("缴款单"+ noticeNo +"更新为已缴款-successCount:{}", successCount);
            //案件主表更新及环节记录保存
            CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(caseId);
            String casePartiesReasonType = caseMainInfoVo.getCasePartiesReasonType();
            String handleType = caseMainInfoVo.getHandleType();
            if (!ObjectUtils.isEmpty(payDate)) {
                //相关字段更新
                ExecuteFinishAutomaticInfoDto param = new ExecuteFinishAutomaticInfoDto();
                param.setCaseId(caseId);
                param.setPayDate(payDate);
                param.setPayMoney(dto.getPayMoney());
            /*
            根据案件当事人类型、处置类型当事人个数
                1.单案由单当事人  1个
                2.单案由多当事人
                     -分别处罚   n个
                     -合并处罚   1个（逗号拼接）
                3.多案由单当事人  1个
             */

                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                String partyId = map.get("partyId");
                String partyName = map.get("partyName");
                boolean isMultiplePartiesAndPartPunish = false;
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
                    isMultiplePartiesAndPartPunish = true;
                    CaseMainDetailAuxiliaryInfo updateInfo = new CaseMainDetailAuxiliaryInfo();
                    updateInfo.setCaseId(caseId);
                    //根据缴款单号查询当事人id
                    CasePaymentMainRecordQueryDto queryPaymentInfo = new CasePaymentMainRecordQueryDto();
                    queryPaymentInfo.setNoticeNo(noticeNo);
                    queryPaymentInfo.setCaseId(caseId);
                    List<CasePaymentMainRecordVo> casePaymentMainRecordList = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryPaymentInfo);
                    if (!ObjectUtils.isEmpty(casePaymentMainRecordList) && casePaymentMainRecordList.size() > 0) {
                        CasePaymentMainRecordVo casePaymentMainRecord = casePaymentMainRecordList.get(Constant.INTEGER_0);
                        String partyIdNew = casePaymentMainRecord.getPartyId();
                        if (ObjectUtils.isEmpty(partyId)) {
                            throw new BusinessException("案件缴费主要信息未记录当事人id");
                        }
                        String[] idArr = partyId.split(",");
                        String[] nameArr = partyName.split(",");
                        for (int i = 0; i < idArr.length; i++) {
                            if (partyIdNew.equals(idArr[i])) {
                                partyName = nameArr[i];
                            }
                        }
                        partyId = partyIdNew;
                    }
                }
                String payMoney = dto.getPayMoney();
                updateCaseInfoAfterExecuteFinishAutomatic(caseId, payMoney, payDate, isMultiplePartiesAndPartPunish ? partyId : null);
                //生成执行情况记录-自动
                dto.setPartyId(partyId);
                dto.setPartyName(partyName);
                generateExecuteConditionAutomaticRecord(dto);
            }

            sendDingMsgAfterPayment(caseMainInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            String errorMsg;
            if (!ObjectUtils.isEmpty(e)) {
                errorMsg = e.getMessage();
            } else {
                errorMsg = "exception is null";
            }
            returnMsg = errorMsg;
        }
        if (!ObjectUtils.isEmpty(returnMsg)) {
            casePaymentResultRecord = new CasePaymentResultRecord();
            casePaymentResultRecord.setDealFailReason(returnMsg);
            casePaymentResultRecord.setCaseId(caseId);
            casePaymentResultRecord.setId(dto.getId());
            updatePaymentResultInfoAfterDeal(casePaymentResultRecord);
        }
        log.info("serviceDealAfterSaveCasePaymentResult end!");
        return returnMsg;
    }

    /**
     * 描述：更新缴款结果处理后的信息
     *
     * @param dto {@link CasePaymentResultRecord}
     * @return int 更新成功记录数
     * @author xiangyuyu
     * @date 2022-07-06 19:41
     */
    @Override
    public int updatePaymentResultInfoAfterDeal(CasePaymentResultRecord dto) {
        String caseId = dto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定caseId");
        }
        int count = casePaymentResultRecordMapper.updatePaymentResultInfoAfterDeal(dto);
        return count;
    }

    /**
     * 描述：更新缴款结果处理简易程序状态
     *
     * @param caseMainInfoVo 案例主要信息签证官
     * @param payMoney       支付的钱
     * @param executeDate    执行日期
     * @return int
     * @author shishengyao
     * @date 2022/12/02
     */
    @Override
    public int updateSimpleCaseStatusAfterPayment(CaseMainInfoVo caseMainInfoVo, String payMoney, LocalDate executeDate) {
        log.info("更新缴款结果处理简易程序状态 start,caseId{}", caseMainInfoVo.getId());
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseMainInfoVo.getId());
        //执行情况信息组装
            /*
            合计执收：人民币叁佰元整（ ¥300.00）。
                1、执收项目：罚款；执收金额：人民币壹佰元整（ ¥100.00）；逾期罚款：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
                2、执收项目：没收违法所得；执收金额：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
             */
        StringBuilder sb = new StringBuilder();
        String tmpPayTotalMoney = ConvertUpMoneyUtil.toChinese(payMoney);
        sb.append("合计执收：人民币");
        sb.append(tmpPayTotalMoney);
        sb.append("（¥");
        sb.append(payMoney);
        sb.append("）。");
        //分类
        String draftPunishMoneyOri = caseMainDetailSimpleInfo.getDraftPunishMoney();
        Map<String, String> map = new HashMap<>(8);
        if (!ObjectUtils.isEmpty(draftPunishMoneyOri)) {
            map.put("罚款", draftPunishMoneyOri);
        }

        AtomicInteger count = new AtomicInteger();
        map.entrySet().forEach(e -> {
            count.getAndIncrement();
            String value = e.getValue();
            sb.append(count + "、执收项目：" + e.getKey() + ";" + "执收金额：人民币"
                    + ConvertUpMoneyUtil.toChinese(value) + "（¥" + value + "）。");
        });
        String executeConditionDesc = sb.toString();

        LocalDateTime now = LocalDateTime.now();
        CaseMainDetailSimpleInfo updateInfo = new CaseMainDetailSimpleInfo();
        updateInfo.setId(caseMainDetailSimpleInfo.getId());
        updateInfo.setExecuteWay("自觉履行");
        updateInfo.setExecuteFinishDate(executeDate);
        updateInfo.setExecuteConditionDesc(executeConditionDesc);
        updateInfo.setUpdateTime(now);
        caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(updateInfo);
        //更新主表
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();

        updateCaseMainInfo.setId(caseMainInfoVo.getId());
        updateCaseMainInfo.setCaseStatus(CaseStatusEnum.END_CASE.getCode());
        updateCaseMainInfo.setCaseEndTime(now);
        //todo 阶段编码默认写死（台州工作流）
        updateCaseMainInfo.setCaseCurrentStageCode("CLOSE_ARCHIVING");
        updateCaseMainInfo.setCaseCurrentStageName("结案");
        updateCaseMainInfo.setCaseCurrentLinkCode("LINK-202203020953");
        updateCaseMainInfo.setCaseCurrentLinkName("归档");
        log.info("更新缴款结果处理简易程序状态 end");
        return caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
    }

    /**
     * 描述：缴款完成发送钉消息
     *
     * @param caseMainInfoVo {@link CaseMainInfoVo}
     * @author xiangyuyu
     * @date 2022-05-26 11:08
     */
    private void sendDingMsgAfterPayment(CaseMainInfoVo caseMainInfoVo) {
        String caseId = caseMainInfoVo.getId();
        try {
            log.info("start send dingMsg-after finish pay  caseId:{}", caseId);
            //发送钉消息
            String caseNumber = caseMainInfoVo.getCaseNumber();
            //获取处罚决定书文书目录编码
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_CFJDS);
            String documentCatalogCode = caseDocumentRecord.getDocumentCatalogCode();

            String punishKinds = "";
            String draftPunishMoney = "";
            String confiscateIllegalMoney = "";
            String caseType = caseMainInfoVo.getCaseType();
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                //简易程序查询简易程序宽表
                CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                punishKinds = caseMainDetailSimpleInfo.getPunishKinds();
                draftPunishMoney = caseMainDetailSimpleInfo.getDraftPunishMoney();

            } else {
                //获取宽表信息
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
                punishKinds = caseMainDetailInfo.getPunishKinds();
                draftPunishMoney = caseMainDetailInfo.getDraftPunishMoney();
                confiscateIllegalMoney = caseMainDetailInfo.getConfiscateIllegalMoney();

                //分别处罚时: 处罚种类,处罚金额及没收违法所得金额处理
                if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfoVo.getHandleType())) {
                    Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
                    auxiliaryExample.createCriteria().andEqualTo("caseId", caseId);
                    List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
                    if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                        //处罚种类
                        Set<String> kindSet = new HashSet<>();
                        //处罚金额
                        BigDecimal punishMoney = new BigDecimal("0");
                        //没收违法所得
                        BigDecimal illegalMoney = new BigDecimal("0");
                        for (CaseMainDetailAuxiliaryInfo auxiliaryInfo : caseMainDetailAuxiliaryInfos) {
                            if (!ObjectUtils.isEmpty(auxiliaryInfo.getPunishKinds())) {
                                String[] split = auxiliaryInfo.getPunishKinds().split(",");
                                Collections.addAll(kindSet, split);
                            }
                            //处罚金额处理
                            if (!ObjectUtils.isEmpty(auxiliaryInfo.getDraftPunishMoney())) {
                                try {
                                    BigDecimal money = new BigDecimal(auxiliaryInfo.getDraftPunishMoney());
                                    punishMoney = punishMoney.add(money);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            //没收违法所得处理
                            if (!ObjectUtils.isEmpty(auxiliaryInfo.getConfiscateIllegalMoney())) {
                                try {
                                    BigDecimal money = new BigDecimal(auxiliaryInfo.getConfiscateIllegalMoney());
                                    illegalMoney = illegalMoney.add(money);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        punishKinds = kindSet.stream().collect(Collectors.joining(","));
                        draftPunishMoney = punishMoney.toString();
                        confiscateIllegalMoney = illegalMoney.toString();
                    }
                }
            }

            double draftPunishMoneyD = 0.0;
            double confiscateIllegalMoneyD = 0.0;
            if (!ObjectUtils.isEmpty(draftPunishMoney)) {
                draftPunishMoneyD = Double.parseDouble(draftPunishMoney);
            }
            if (!ObjectUtils.isEmpty(confiscateIllegalMoney)) {
                confiscateIllegalMoneyD = Double.parseDouble(confiscateIllegalMoney);
            }
            Double totalPunishMoney = draftPunishMoneyD + confiscateIllegalMoneyD;
            //获取办案人员信息
            List<CaseHandlePersonRecordVo> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
            //不管是自动还是非自动执行完成，最多有且只会有1条执行记录
            CaseDocumentRecord documentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, "ZXQKHCJL");
            //获取文书目录编码
            if (ObjectUtils.isEmpty(documentRecord)) {
                throw new BusinessException("未匹配到执行情况记录-caseId:" + caseId);
            }
            String documentCatalogCodeExecuteFinish = documentRecord.getDocumentCatalogCode();
            String finalPunishKinds = punishKinds;
            caseHandlePersonRecordList.forEach(e -> {
                String dingId = e.getDingId();
                String handlerName = e.getHandlePersonName();
                if (!ObjectUtils.isEmpty(dingId)) {
                    //自动执行完成钉消息
                    DingDingUtil.autoAuditMsg(caseId, documentCatalogCodeExecuteFinish, caseNumber, finalPunishKinds, dingId, handlerName, totalPunishMoney.toString(), "");

                    //工作台-消息提醒
                    sendAutoAuditMsg(caseId, caseNumber, finalPunishKinds, totalPunishMoney, e, caseMainInfoVo);

                    //缴款结束钉消息
                    //只抽取涉及到收费的处罚种类(罚款,没收违法所得)
                    StringBuilder punishMoneyKindSb = new StringBuilder();
                    if (finalPunishKinds.contains("罚款")) {
                        punishMoneyKindSb.append("罚款,");
                    }
                    if (finalPunishKinds.contains("没收违法所得")) {
                        punishMoneyKindSb.append("没收违法所得");
                    }
                    String punishMoneyKind = punishMoneyKindSb.toString();
                    if (punishMoneyKind.endsWith(Constant.STRING_COMMA)) {
                        punishMoneyKind = punishMoneyKind.substring(0, punishMoneyKind.length() - 1);
                    }
                    DingDingUtil.payFinishMsg(caseId, documentCatalogCode, caseNumber, punishMoneyKind, dingId, handlerName, totalPunishMoney.toString(), "");
                    //工作台-消息提醒
                    sendPayFinishMsg(caseId, caseNumber, punishMoneyKind, totalPunishMoney, e, caseMainInfoVo);
                }
            });
            log.info("send dingMsg-after finish pay end caseId:{}", caseId);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("send dingMsg error-after finish pay caseId:{},e.msg:{}", caseId, e.getMessage());
        }
    }

    /**
     * 描述：生成执行情况核查记录-自动
     *
     * @param dto {@link CasePaymentResultRecordSaveDto}
     * @author xiangyuyu
     * @date 2022-04-25 15:11
     */
    private void generateExecuteConditionAutomaticRecord(CasePaymentResultRecordSaveDto dto) {
        HashMap<String, Object> dataMap = new HashMap<>(20);
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        String partyId = dto.getPartyId();
        String partyName = dto.getPartyName();
        String caseId = dto.getCaseId();

        dataMap.put("ZXQKJL_AUTO_DSR", partyName);
        //获取案件信息
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String handleType = caseMainInfo.getHandleType();
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        LocalDate executeFinishDate;
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)
                && PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)) {
            //获取补充表数据
            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest(caseId, partyId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfoList = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            if (ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfoList) || caseMainDetailAuxiliaryInfoList.size() == 0) {
                throw new BusinessException("未匹配到案件补充表详情-caseId：" + caseId + "，partyId：" + partyId);
            }
            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfoList.get(Constant.INTEGER_0);
            executeFinishDate = caseMainDetailAuxiliaryInfo.getExecuteFinishDate();
            if (ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfo)) {
                throw new BusinessException("未匹配到案件详情-caseId：" + caseId);
            }

            //执行方式
            String executeWay = caseMainDetailAuxiliaryInfo.getExecuteWay();
            dataMap.put("ZXQKJL_AUTO_ZXFS", executeWay);
            //执行情况描述
            String executeConditionDesc = caseMainDetailAuxiliaryInfo.getExecuteConditionDesc();
            dataMap.put("ZXQKJL_AUTO_ZXJCQK", executeConditionDesc);
            String documentNumber = caseMainDetailAuxiliaryInfo.getPunishDocumentNumber();
            dataMap.put("ZXQKJL_AUTO_BZ", documentNumber);
        } else {
            //获取宽表信息
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
            executeFinishDate = caseMainDetailInfo.getExecuteFinishDate();
            if (ObjectUtils.isEmpty(caseMainDetailInfo)) {
                throw new BusinessException("未匹配到案件详情-caseId：" + caseId);
            }
            //执行方式
            String executeWay = caseMainDetailInfo.getExecuteWay();
            dataMap.put("ZXQKJL_AUTO_ZXFS", executeWay);
            //执行情况描述
            String executeConditionDesc = caseMainDetailInfo.getExecuteConditionDesc();
            dataMap.put("ZXQKJL_AUTO_ZXJCQK", executeConditionDesc);
            String documentNumber = caseMainDetailInfo.getPunishDocumentNumber();
            dataMap.put("ZXQKJL_AUTO_BZ", documentNumber);
        }


        String tmp = executeFinishDate.format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        //执行完成日期
        dataMap.put("ZXQKJL_AUTO_ZXWCRQ", tmp);
        //获取缴款结果信息
        CasePaymentResultRecordVo resultInfo = getCasePaymentResultRecordDetailByCaseId(caseId);
        //缴款单号
        String noticeNo = resultInfo.getNoticeNo();
        dataMap.put("ZXQKJL_AUTO_JKDH", noticeNo);
        //缴款日期
        dataMap.put("ZXQKJL_AUTO_JKRQ", resultInfo.getPayDate());
        //缴款凭证号
        dataMap.put("ZXQKJL_AUTO_JKPZH", resultInfo.getCertificateNo());
        //缴款凭证校验码
        dataMap.put("ZXQKJL_AUTO_JKPZJYM", resultInfo.getCheckCode());
        //代收机构	ZXQKJL_AUTO_DSJG
        dataMap.put("ZXQKJL_AUTO_DSJG", resultInfo.getTradeName());
        //支付方式	ZXQKJL_AUTO_ZFFS
        dataMap.put("ZXQKJL_AUTO_ZFFS", resultInfo.getWayName());

        //查询缴费项目明细表
        CasePaymentMainRecordQueryDto queryPaymentMain = new CasePaymentMainRecordQueryDto();
        queryPaymentMain.setCaseId(caseId);
        queryPaymentMain.setNoticeNo(noticeNo);
        List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryPaymentMain);
        if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
            CasePaymentMainRecordVo casePaymentMainRecord = list.get(Constant.INTEGER_0);
            //查询缴款主要信息记录表的主键id
            String paymentId = casePaymentMainRecord.getId();
            CasePaymentItemDetailQueryDto queryDto = new CasePaymentItemDetailQueryDto();
            queryDto.setPaymentId(paymentId);
            List<CasePaymentItemDetailVo> itemList = casePaymentItemDetailService.getCasePaymentItemDetailInfo(queryDto);
            if (!ObjectUtils.isEmpty(itemList) && itemList.size() > 0) {
                //目前只取一条
                CasePaymentItemDetailVo itemInfo = itemList.get(Constant.INTEGER_0);
                //项目编码	ZXQKJL_AUTO_XMBM
                dataMap.put("ZXQKJL_AUTO_XMBM", itemInfo.getChitCode());
                //项目名称	ZXQKJL_AUTO_XMMC
                dataMap.put("ZXQKJL_AUTO_XMMC", itemInfo.getChitName());
                //证据描述-单位	ZXQKJL_AUTO_ZJMS_DW
                dataMap.put("ZXQKJL_AUTO_ZJMS_DW", itemInfo.getMetricUnit());
                //证据描述-数量	ZXQKJL_AUTO_ZJMS_SL
                dataMap.put("ZXQKJL_AUTO_ZJMS_SL", itemInfo.getChCount());
                //证据描述-标准	ZXQKJL_AUTO_ZJMS_STANDARD
                dataMap.put("ZXQKJL_AUTO_ZJMS_STANDARD", itemInfo.getChargeStandard());
                //证据描述-金额	ZXQKJL_AUTO_ZJMS_JE
                dataMap.put("ZXQKJL_AUTO_ZJMS_JE", itemInfo.getChMoney());
                //证据描述-备注	ZXQKJL_AUTO_ZJMS_BZ
                dataMap.put("ZXQKJL_AUTO_ZJMS_BZ", "");
            }
        }
        //证据原件	ZXQKJL_AUTO_ZJYJ
        List<Object> zjyjList = new ArrayList<>();
        List<String> electricInvoiceInfo = dto.getElectricInvoiceInfo();
        String documentCatalogCode = Constant.STRING_DOCUMENT_CATALOG_CODE_AUTO_ZXQKJL;
        if (!ObjectUtils.isEmpty(electricInvoiceInfo) && electricInvoiceInfo.size() > 0) {
            Map<String, String> zjyjMap = new HashMap<>(20);
            electricInvoiceInfo.forEach(e -> {
                //将电子发票转换为图片
                //String imageBase64 = PdfUtil.pdfTransImage(e);
                //zjyjMap.put("ZXQKJL_AUTO_ZJYJ","data:image/jpg;base64,"+e);
                //zjyjMap.put("ZXQKJL_AUTO_ZJYJ","data:application/pdf;base64,"+e);
                zjyjMap.put("ZXQKJL_AUTO_ZJYJ","data:image/png;base64,"+ e);
                zjyjList.add(zjyjMap);
                //添加电子发票附件
                addAttachmentElectricInvoice(caseMainInfo, documentCatalogCode, dto.getElectricInvoiceAddress(), partyId);
            });
        }
        dataMap.put("ZJYJ_AUTO_LIST", zjyjList);
        //获取办案人员
        List<CaseHandlePersonRecordVo> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        String mainHandlerName = "";
        String assistHandlerName = "";

        String mainHandlerCert = "";
        String assistHandlerCert = "";
        for (CaseHandlePersonRecordVo handler : caseHandlePersonRecordList) {
            String handlePersonType = handler.getHandlePersonType();
            if (Constant.STRING_1.equals(handlePersonType)) {
                //主办
                mainHandlerName = handler.getHandlePersonName();
                mainHandlerCert = handler.getLawEnforcementCert();
            } else {
                //协办
                assistHandlerName = handler.getHandlePersonName();
                assistHandlerCert = handler.getLawEnforcementCert();
            }
            if (!ObjectUtils.isEmpty(mainHandlerName) && !ObjectUtils.isEmpty(assistHandlerName)) {
                break;
            }
        }
        dataMap.put("ZXQKJL_AUTO_ZBRYXM", mainHandlerName);
        dataMap.put("ZXQKJL_AUTO_ZBRYZFZH", mainHandlerCert);
        dataMap.put("ZXQKJL_AUTO_XBRYXM", assistHandlerName);
        dataMap.put("ZXQKJL_AUTO_XBRYZFZH", assistHandlerCert);
        //处罚决定书文号 CFJDSWH
        String kindCode = Constant.STRING_KIND_CODE_CFJDS;
        CaseDocumentRecordDto documentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, kindCode);
        if (ObjectUtils.isEmpty(documentRecord)) {
            throw new BusinessException("未匹配到处罚决定书信息-caseId:" + caseId + ",kindCode:" + kindCode);
        }
        saveDto.setCaseId(caseId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        saveDto.setDataMap(dataMap);
        saveDto.setIsUpdateRelationTable(YesOrNoEnum.NO.getCode());
        saveDto.setPartyId(partyId);
        stageDocCommonOperateService.saveDocInfo(saveDto);
    }

    /**
     * 描述：添加电子发票附件信息
     *
     * @param caseMainInfo           {@link CaseMainInfoVo}
     * @param documentCatalogCode    文书目录编码
     * @param electricInvoiceAddress 电子发票地址
     * @param partyId                当事人id
     * @return boolean 是否成功
     * @author xiangyuyu
     * @date 2022/9/8
     * @since 添加电子发票附件信息
     */
    @Override
    public boolean addAttachmentElectricInvoice(CaseMainInfoVo caseMainInfo, String documentCatalogCode, String electricInvoiceAddress, String partyId) {
        Example example = new Example(CaseAppendixRecord.class);
        Example.Criteria c = example.createCriteria();
        String caseId = caseMainInfo.getId();
        c.andEqualTo("caseId", caseId);
        c.andEqualTo("isDelete", Constant.STRING_0);
        if (!ObjectUtils.isEmpty(partyId)) {
            c.andEqualTo("partyId", partyId);
        }
        c.andEqualTo("appendixTypeId", AttachmentTypeEnum.PAYMENT_PROOF.getCode());
        c.andEqualTo("appendixName", "电子发票.pdf");
        c.andEqualTo("uploadUserName", "system");
        int count = caseAppendixRecordMapper.selectCountByExample(example);
        if (count == 0) {
            CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
            caseAppendixRecord.setId(BaseUtil.createUid());
            caseAppendixRecord.setCaseId(caseId);
            caseAppendixRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
            caseAppendixRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
            caseAppendixRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
            caseAppendixRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
            caseAppendixRecord.setDocumentCatalogCode(documentCatalogCode);
            caseAppendixRecord.setAppendixName("电子发票.pdf");
            caseAppendixRecord.setUploadUserId(Constant.STRING_0);
            caseAppendixRecord.setUploadUserName("system");
            caseAppendixRecord.setUploadTime(LocalDateTime.now());
            caseAppendixRecord.setAppendixUrl(electricInvoiceAddress);
            caseAppendixRecord.setAppendixTypeId(AttachmentTypeEnum.PAYMENT_PROOF.getCode());
            caseAppendixRecord.setPartyId(partyId);
            caseAppendixRecordMapper.insertSelective(caseAppendixRecord);
        }
        return true;
    }

    /**
     * 批量处理：缴款后，没有自动生成执行情况核查记录文书的问题
     *
     * @param caseId
     * @return
     */
    @Override
    public boolean batchRebuildExecuteCheckDoc(String caseId) {
        List<CasePaymentResultRecordSaveDto> reList = casePaymentResultRecordMapper.batchRebuildExecuteCheckDoc(caseId);
        for (CasePaymentResultRecordSaveDto dto : reList) {
            if (StrUtil.isNotEmpty(dto.getElectricInvoiceAddress())) {
                List<String> list = new ArrayList<>();
                list.add(dto.getElectricInvoiceAddress());
                dto.setElectricInvoiceInfo(list);
            }
            //执行
            try {
                this.saveCasePaymentResultRecordInfo(dto);
            } catch (Exception e) {
                log.warn("-----------生成执行情况记录文书报错-----------", e);
            }
        }
        return true;
    }

    /**
     * 描述：自动执行完毕后案件信息更新
     *
     * @param caseId   案件id
     * @param payMoney 缴款金额
     * @param payDate  缴款日期
     * @param partyId  当事人id
     * @author xiangyuyu
     * @date 2022-04-24 14:07
     */
    private void updateCaseInfoAfterExecuteFinishAutomatic(String caseId, String payMoney, String payDate, String partyId) {
        log.info("updateCaseInfoAfterExecuteFinishAutomatic start... caseId:{},payMoney:{},payDate:{},partyId:{}", caseId, payMoney, payDate, partyId);


        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String handleType = caseMainInfo.getHandleType();
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();

        Example example;
        //更新成功记录数
        int uc;
        LocalDate executeDate = LocalDate.parse(payDate, DateTimeFormatter.ofPattern("yyyyMMdd"));
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)
                && PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)) {

            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest(caseId, partyId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfoList = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            if (ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfoList) || caseMainDetailAuxiliaryInfoList.size() == 0) {
                throw new BusinessException("未匹配到案件补充表详情-caseId：" + caseId + "，partyId：" + partyId);
            }
            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfoList.get(Constant.INTEGER_0);
            if (ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfo)) {
                throw new BusinessException("updateCaseInfoAfterExecuteFinishAutomatic not found detailInfo-caseId:" + caseId);
            }

            caseMainDetailAuxiliaryInfo.setExecuteFinishDate(executeDate);
            caseMainDetailAuxiliaryInfo.setExecuteWay("自觉履行");
            //执行情况信息组装
            /*
            合计执收：人民币叁佰元整（ ¥300.00）。
                1、执收项目：罚款；执收金额：人民币壹佰元整（ ¥100.00）；逾期罚款：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
                2、执收项目：没收违法所得；执收金额：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
             */
            StringBuilder sb = new StringBuilder();
            String tmpPayTotalMoney = ConvertUpMoneyUtil.toChinese(payMoney);
            sb.append("合计执收：人民币");
            sb.append(tmpPayTotalMoney);
            sb.append("（¥");
            sb.append(payMoney);
            sb.append("）。\n");
            //分类
            String draftPunishMoneyOri = caseMainDetailAuxiliaryInfo.getDraftPunishMoney();
            String confiscateIllegalMoneyOri = caseMainDetailAuxiliaryInfo.getConfiscateIllegalMoney();
            Map<String, String> map = new HashMap<>(8);
            if (!ObjectUtils.isEmpty(draftPunishMoneyOri)) {
                map.put("罚款", draftPunishMoneyOri);
            }
            if (!ObjectUtils.isEmpty(confiscateIllegalMoneyOri)) {
                map.put("没收违法所得", confiscateIllegalMoneyOri);
            }
            AtomicInteger count = new AtomicInteger();
            map.entrySet().forEach(e -> {
                count.getAndIncrement();
                String value = e.getValue();
                sb.append(count + "、执收项目：" + e.getKey() + ";" + "执收金额：人民币"
                        + ConvertUpMoneyUtil.toChinese(value) + "（¥" + value + "）。");
            });
            String executeConditionDesc = sb.toString();
            caseMainDetailAuxiliaryInfo.setExecuteConditionDesc(executeConditionDesc);

            example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("partyId", partyId);
            uc = caseMainDetailAuxiliaryInfoMapper.updateByExample(caseMainDetailAuxiliaryInfo, example);
            boolean isAllBranchFlowExecuteFinish = caseExecuteService.dealAfterAllBranchFlowExecuteFinish(caseId);
            log.info(isAllBranchFlowExecuteFinish ? "after receive pay result:all branch flow execute finish" : "exists not execute finish branch");
        } else {
            //简易程序更新
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                uc = updateSimpleCaseStatusAfterPayment(caseMainInfo, payMoney, executeDate);
            }
            //普通程序
            else {
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
                if (ObjectUtils.isEmpty(caseMainDetailInfo)) {
                    throw new BusinessException("updateCaseInfoAfterExecuteFinishAutomatic not found detailInfo-caseId:" + caseId);
                }
                caseMainDetailInfo.setExecuteFinishDate(executeDate);
                caseMainDetailInfo.setExecuteWay("自觉履行");
                //执行情况信息组装
            /*
            合计执收：人民币叁佰元整（ ¥300.00）。
                1、执收项目：罚款；执收金额：人民币壹佰元整（ ¥100.00）；逾期罚款：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
                2、执收项目：没收违法所得；执收金额：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
             */
                StringBuilder sb = new StringBuilder();
                String tmpPayTotalMoney = ConvertUpMoneyUtil.toChinese(payMoney);
                sb.append("合计执收：人民币");
                sb.append(tmpPayTotalMoney);
                sb.append("（¥");
                sb.append(payMoney);
                sb.append("）。\n");
                //分类
                String draftPunishMoneyOri = caseMainDetailInfo.getDraftPunishMoney();
                String confiscateIllegalMoneyOri = caseMainDetailInfo.getConfiscateIllegalMoney();
                Map<String, String> map = new HashMap<>(8);
                if (!ObjectUtils.isEmpty(draftPunishMoneyOri)) {
                    map.put("罚款", draftPunishMoneyOri);
                }
                if (!ObjectUtils.isEmpty(confiscateIllegalMoneyOri)) {
                    map.put("没收违法所得", confiscateIllegalMoneyOri);
                }

                AtomicInteger count = new AtomicInteger();
                map.entrySet().forEach(e -> {
                    count.getAndIncrement();
                    String value = e.getValue();
                    sb.append(count + "、执收项目：" + e.getKey() + ";" + "执收金额：人民币"
                            + ConvertUpMoneyUtil.toChinese(value) + "（¥" + value + "）。");
                });
                String executeConditionDesc = sb.toString();
                caseMainDetailInfo.setExecuteConditionDesc(executeConditionDesc);
                uc = caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
            }

        }


        if (Constant.INTEGER_1 == uc) {
            log.info("updateCaseInfoAfterExecuteFinishAutomatic success");
        } else {
            log.info("updateCaseInfoAfterExecuteFinishAutomatic fail uc:{}", uc);
        }
        log.info("updateCaseInfoAfterExecuteFinishAutomatic end");
    }

    /**
     * 【V1.0.0】描述：获取案件缴款结果记录详情
     *
     * @param queryDto {@link CasePaymentResultRecordQueryDto}
     * @return {@link CasePaymentResultRecordVo} 案件缴款结果记录详情
     * @author xiangyuyu
     * @date 2022-03-02 15:23
     */
    @Override
    public CasePaymentResultRecordVo getCasePaymentResultRecordDetail(CasePaymentResultRecordQueryDto queryDto) {
        String noticeNo = queryDto.getNoticeNo();
        if (ObjectUtils.isEmpty(noticeNo)) {
            throw new BusinessException("未指定缴款单号");
        }
        CasePaymentResultRecordVo vo = casePaymentResultRecordMapper.selectCasePaymentResultRecordDetail(queryDto);
        return vo;
    }

    /**
     * 【V1.1.0】描述：根据案件id查询最新缴款结果信息
     *
     * @param caseId 案件id
     * @return {@link CasePaymentResultRecordVo} 案件缴款结果记录详情
     * @author xiangyuyu
     * @date 2022-04-25 15:34
     */
    @Override
    public CasePaymentResultRecordVo getCasePaymentResultRecordDetailByCaseId(String caseId) {
        Example e = new Example(CasePaymentResultRecord.class);
        e.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
        e.setOrderByClause("create_time desc");
        List<CasePaymentResultRecord> list = casePaymentResultRecordMapper.selectByExample(e);
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            throw new BusinessException("未匹配到该案件的缴款结果信息-caseId：" + caseId);
        }
        CasePaymentResultRecord record = list.get(Constant.INTEGER_0);
        CasePaymentResultRecordVo vo = new CasePaymentResultRecordVo();
        BeanUtils.copyProperties(record, vo);
        vo.setElectricInvoiceAddress(record.getElcInvoicePicUrl());
        return vo;
    }

    /**
     * 【V1.3.1】描述：查询统一支付缴款结果信息
     *
     * @param queryDto {@link PaymentResultInfoDto}
     * @return {@link PaymentResultInfo} 支付结果信息
     * @author xiangyuyu
     * @date 2022-07-11 16:25
     */
    @Override
    public PaymentResultInfo getPaymentResultInfo(BusQueryPayStatusModelDto queryDto) {
        log.info("getPaymentResultInfo start... queryDto:{}", queryDto);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(queryDto);
        String jsonParam = jsonObject.toJSONString();
        log.info("jsonParam:{}", jsonParam);
        PaymentResultInfo paymentResultInfo = new PaymentResultInfo();
        try {
            String result = HttpUtils.doPostJson(busQueryPayStatusUrl, jsonParam);
            if (!ObjectUtils.isEmpty(result)) {
                JSONObject responseJson = JSONObject.parseObject(result);
                if (!ObjectUtils.isEmpty(responseJson)) {
                    String isConfirm =responseJson.getString("isConfirm");
                    if(!Constant.STRING_1.equals(isConfirm)){
                        return paymentResultInfo;
                    }
                    paymentResultInfo.setNoticeNo(responseJson.getString("docNumber"));
                    paymentResultInfo.setPayMoney(responseJson.getString("paymentTotal"));
                    paymentResultInfo.setChannelNo(responseJson.getString("payChannel"));
                    paymentResultInfo.setIsConfirm(isConfirm);
                    String confirmDateStr=responseJson.getString("confirmDate");
                    Date confirmDate = DateUtils.parseDate(confirmDateStr, "yyyy-MM-dd HH:mm:ss");
                    String payDate = DateUtils.formatDate(confirmDate, "yyyyMMdd");
                    String payTime = DateUtils.formatDate(confirmDate, "HHmmss");
                    paymentResultInfo.setPayDate(payDate);
                    paymentResultInfo.setPayTime(payTime);
                    paymentResultInfo.setOriginalNoticeNo(responseJson.getString("orderNo"));
                    paymentResultInfo.setCertificateNo(responseJson.getString("payCode"));
                    paymentResultInfo.setNoticeNo(responseJson.getString("docNumber"));
                    paymentResultInfo.setElectricInvoiceAddress(jsonObject.getString("billH5Url"));
                    String billBatchCode = jsonObject.getString("billBatchCode");
                    String billNo = jsonObject.getString("billNo");
                    String billRandom = jsonObject.getString("billRandom");
                    List<String> electricInvoiceInfo = new ArrayList<>();
                    electricInvoiceInfo.add(billBatchCode);
                    electricInvoiceInfo.add(billNo);
                    electricInvoiceInfo.add(billRandom);
                    paymentResultInfo.setElectricInvoiceInfo(electricInvoiceInfo);
                    //paymentResultInfo = responseJson.toJavaObject(PaymentResultInfo.class);
                } else {
                    log.warn("getPaymentResultInfo response data is null");
                }
            } else {
                log.warn("getPaymentResultInfo response is null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warn(e.getMessage());
        }
        log.info("getPaymentResultInfo end PaymentResultInfo:{}", paymentResultInfo);
        return paymentResultInfo;
    }

    /**
     * 【V1.3.1】描述：获取统一支付缴款结果保存并进行案件处理
     *
     * @param dto {@link PaymentResultDealDto}
     * @return {@link Result<String>} 操作结果
     * @author xiangyuyu
     * @date 2022-07-12 19:33
     */
    @Override
    public Result<String> savePaymentResultAndDealCaseInfo(PaymentResultDealDto dto) {
        List<String> noticeNoList = dto.getNoticeNoList();
        if (ObjectUtils.isEmpty(noticeNoList) || noticeNoList.size() == 0) {
            return Result.error("未指定需要处理的缴款单号列表");
        }
        StringBuilder errorMsgTotal = new StringBuilder();
        for (String e : noticeNoList) {
            try {
                //获取缴款基础信息（缴款单号、业务号、渠道号等）
                CasePaymentMainRecordQueryDto queryDto = new CasePaymentMainRecordQueryDto();
                queryDto.setNoticeNo(e);
                List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryDto);
                if (ObjectUtils.isEmpty(list) || list.size() == 0) {
                    errorMsgTotal.append("noticeNo:" + e + " not found basic info;");
                } else {
                    //取第一条
                    CasePaymentMainRecordVo vo = list.get(Constant.INTEGER_0);
                    String channelNo = vo.getChannelNo();
                    String originalNoticeNo = vo.getOriginalNoticeNo();
                    if (ObjectUtils.isEmpty(channelNo) || ObjectUtils.isEmpty(originalNoticeNo)) {
                        errorMsgTotal.append("noticeNo:" + e + " basic info not complete[channelNo:" + channelNo + ",originalNoticeNo:" + originalNoticeNo + "];");
                    } else {
                        //查询缴款结果
                        //PaymentResultInfoDto paymentResultInfoDto = new PaymentResultInfoDto(e, originalNoticeNo, channelNo);
                        BusQueryPayStatusModelDto busQueryPayStatusModelDto=new BusQueryPayStatusModelDto();
                        busQueryPayStatusModelDto.setDocNumber(vo.getNoticeNo());
                        busQueryPayStatusModelDto.setDeptId(vo.getEnterCode());
                        PaymentResultInfo paymentResultInfo = getPaymentResultInfo(busQueryPayStatusModelDto);
                        if (ObjectUtils.isEmpty(paymentResultInfo)) {
                            errorMsgTotal.append("noticeNo:" + e + " not found payment result;");
                        } else {
                            CasePaymentResultRecordSaveDto saveDto = new CasePaymentResultRecordSaveDto();
                            BeanUtils.copyProperties(paymentResultInfo, saveDto);
                            Result<String> saveResult = saveCasePaymentResultRecordInfo(saveDto);
                            if (HttpStatus.HTTP_OK == saveResult.getCode()) {
                                errorMsgTotal.append("noticeNo:" + e + " success;");
                            } else {
                                errorMsgTotal.append("noticeNo:" + e + " saveCasePaymentResultRecordInfo fail[" + saveResult.getMessage() + "];");
                            }
                        }
                    }
                }

            }catch (Exception ex){
                ex.printStackTrace();
                continue;
            }

        }
        if (!ObjectUtils.isEmpty(errorMsgTotal)) {
            return Result.success(errorMsgTotal.toString());
        }
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 工作台-案件自动执行完毕提醒
     *
     * @param caseId                   案件id
     * @param caseNumber               案件编号
     * @param punishType               处罚种类
     * @param money                    缴费金额
     * @param caseHandlePersonRecordVo 案件流程实体
     * @param caseMainInfoVo           案件实体
     * @author yangsizhen
     * @date 2022/12/13
     */
    private void sendAutoAuditMsg(String caseId, String caseNumber, String punishType, Double money, CaseHandlePersonRecordVo caseHandlePersonRecordVo, CaseMainInfoVo caseMainInfoVo) {
        String title = "案件自动执行完毕";
        String msg = "您编号【" + caseNumber + "】的案件自动执行完成。"
                + "\n\n处罚种类：" + punishType
                + "\n\n缴费金额：人民币 " + money + "元整";
        SystemMessageInsertDto dto = new SystemMessageInsertDto();
        dto.setContent(msg);
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("caseId", caseId);
        paramMap.put("caseCurrentStageName", caseMainInfoVo.getCaseCurrentStageName());
        paramMap.put("dataSource", null);
        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        dto.setParamsJson(json);
        dto.setReceiverDept(caseHandlePersonRecordVo.getHandleOrgCode());
        dto.setReceiverId(caseHandlePersonRecordVo.getHandlePersonId());
        dto.setTitle(title);
        dto.setType("5");
        caseSystemMessageService.insertSystemMessage(dto);
    }

    /**
     * 工作台-案件缴费完成提醒
     *
     * @param caseId                   案件id
     * @param caseNumber               办案机构
     * @param payType                  缴费种类
     * @param money                    缴费金额
     * @param caseHandlePersonRecordVo 案件流程实体
     * @param caseMainInfoVo           案件实体
     * @author yangsizhen
     * @date 2022/12/13
     */
    private void sendPayFinishMsg(String caseId, String caseNumber, String payType, Double money, CaseHandlePersonRecordVo caseHandlePersonRecordVo, CaseMainInfoVo caseMainInfoVo) {
        String title = "案件缴费完成提示";
        String msg = "您编号【" + caseNumber + "】的案件缴费已完成。"
                + "\n\n缴费种类：" + payType
                + "\n\n缴费金额：人民币" + money + "元";
        SystemMessageInsertDto dto = new SystemMessageInsertDto();
        dto.setContent(msg);
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("caseId", caseId);
        paramMap.put("caseCurrentStageName", caseMainInfoVo.getCaseCurrentStageName());
        paramMap.put("dataSource", null);
        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        dto.setParamsJson(json);
        dto.setReceiverDept(caseHandlePersonRecordVo.getHandleOrgCode());
        dto.setReceiverId(caseHandlePersonRecordVo.getHandlePersonId());
        dto.setTitle(title);
        dto.setType("6");
        caseSystemMessageService.insertSystemMessage(dto);
    }


    /**
     * 描述：根据缴款结果处理历史简易程序的状态
     *
     * @param caseMainInfoVo 案件详情表vo
     * @param resultRecordVo 缴款结果vo
     * @return int
     * @author shishengyao
     * @date 2023/01/05
     */
    @Override
    public int updateSimpleCaseStatusByHistoryPaymentRecord(CaseMainInfoVo caseMainInfoVo, CasePaymentResultRecordVo resultRecordVo) {
        LocalDate executeDate = LocalDate.parse(resultRecordVo.getPayDate(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        String payTime = ObjectUtils.isEmpty(resultRecordVo.getPayTime()) ? "000000" : resultRecordVo.getPayTime();
        LocalDateTime executeDateTime = LocalDateTime.parse(resultRecordVo.getPayDate()+payTime, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseMainInfoVo.getId());
        //执行情况信息组装
            /*
            合计执收：人民币叁佰元整（ ¥300.00）。
                1、执收项目：罚款；执收金额：人民币壹佰元整（ ¥100.00）；逾期罚款：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
                2、执收项目：没收违法所得；执收金额：人民币壹佰元整（ ¥100.00）；小计执收：人民币贰佰元整（ ¥200.00）。
             */
        String payMoney = resultRecordVo.getPayMoney();
        StringBuilder sb = new StringBuilder();
        String tmpPayTotalMoney = ConvertUpMoneyUtil.toChinese(payMoney);
        sb.append("合计执收：人民币");
        sb.append(tmpPayTotalMoney);
        sb.append("（¥");
        sb.append(payMoney);
        sb.append("）。");
        //分类
        String draftPunishMoneyOri = caseMainDetailSimpleInfo.getDraftPunishMoney();
        Map<String, String> map = new HashMap<>(8);
        if (!ObjectUtils.isEmpty(draftPunishMoneyOri)) {
            map.put("罚款", draftPunishMoneyOri);
        }

        AtomicInteger count = new AtomicInteger();
        map.entrySet().forEach(e -> {
            count.getAndIncrement();
            String value = e.getValue();
            sb.append(count + "、执收项目：" + e.getKey() + ";" + "执收金额：人民币"
                    + ConvertUpMoneyUtil.toChinese(value) + "（¥" + value + "）。");
        });
        String executeConditionDesc = sb.toString();
        //更新主表
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        if (CaseStatusEnum.HANDLING_CASE.getCode().equals(caseMainInfoVo.getCaseStatus())){
            updateCaseMainInfo.setId(caseMainInfoVo.getId());
            updateCaseMainInfo.setCaseStatus(CaseStatusEnum.END_CASE.getCode());
            updateCaseMainInfo.setCaseEndTime(executeDateTime);
            //todo 阶段编码默认写死（台州工作流）
            updateCaseMainInfo.setCaseCurrentStageCode("CLOSE_ARCHIVING");
            updateCaseMainInfo.setCaseCurrentStageName("结案");
            updateCaseMainInfo.setCaseCurrentLinkCode("LINK-202203020953");
            updateCaseMainInfo.setCaseCurrentLinkName("归档");
            log.info("更新缴款结果处理简易程序状态 end");
            return caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
        }
        CaseMainDetailSimpleInfo updateInfo = new CaseMainDetailSimpleInfo();
        updateInfo.setId(caseMainDetailSimpleInfo.getId());
        updateInfo.setExecuteWay("自觉履行");
        updateInfo.setExecuteFinishDate(executeDate);
        updateInfo.setExecuteConditionDesc(executeConditionDesc);
        return  caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(updateInfo);
    }

    @Override
    public CasePaymentResultRecord getCasePaymentResultByCaseId(String caseId) {
        Example e = new Example(CasePaymentResultRecord.class);
        e.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
        e.setOrderByClause("create_time desc");
        List<CasePaymentResultRecord> list = casePaymentResultRecordMapper.selectByExample(e);
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            return null;
        }else{
            return list.get(0);
        }
    }
}
